-- ________  ________  ________   ________  ________  _____ ______           ___  ___  _________  ___  ___
--|\   __  \|\   __  \|\   ___  \|\   ___ \|\   __  \|\   _ \  _   \        |\  \|\  \|\___   ___\\  \|\  \
--\ \  \|\  \ \  \|\  \ \  \\ \  \ \  \_|\ \ \  \|\  \ \  \\\__\ \  \       \ \  \\\  \|___ \  \_\ \  \ \  \
-- \ \   _  _\ \   __  \ \  \\ \  \ \  \ \\ \ \  \\\  \ \  \\|__| \  \       \ \  \\\  \   \ \  \ \ \  \ \  \
--  \ \  \\  \\ \  \ \  \ \  \\ \  \ \  \_\\ \ \  \\\  \ \  \    \ \  \       \ \  \\\  \   \ \  \ \ \  \ \  \____
--   \ \__\\ _\\ \__\ \__\ \__\\ \__\ \_______\ \_______\ \__\    \ \__\       \ \_______\   \ \__\ \ \__\ \_______\
--    \|__|\|__|\|__|\|__|\|__| \|__|\|_______|\|_______|\|__|     \|__|        \|_______|    \|__|  \|__|\|_______|
-- banner online tools
-- https://www.bootschool.net/ascii;bsid=FB5C2059677902AEBA0B2640589E9FE8

local require  = require;
local ngx      = ngx;
local debug    = debug;
local string   = string;
local tonumber = tonumber;
local setmetatable = setmetatable
local pairs    = pairs
local type     = type
local table    = table
local ipairs   = ipairs

local table_concat     = table.concat

local math       = math
local math_floor = math.floor

local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");
local ns_time    = require("modules.commhm.time");


--- 特性:
---


local _M = { _VERSION = '0.12.1' }
local mt = { __index = _M }

math.randomseed(os.time())


---洗牌算法，用于将一组数据等概率随机打乱。等概率算法。
---@param t	table	待打乱的数组
function _M.shuffle(t)
	if (not t) or type(t)~="table" then return end
	local cnt = #t
	for i=1,cnt do
		local j = math.random(1,cnt)
		t[i],t[j] = t[j],t[i]
	end
end

---浅拷贝
---@param src	table	待拷贝的table
---@return table	拷贝好的新table
local function shallow_copy(src)
	local dst = {}
	for k,v in pairs(src) do
		dst[k] = v;
	end
	return dst
end

---深拷贝
---@param src	table	待拷贝的table
---@return table	拷贝好的新table
local function deep_copy(src)
	local function copy(org, res)
		for k,v in pairs(org) do
			if type(v) ~= "table" then
				res[k] = v;
			else
				res[k] = {};
				copy(v, res[k])
			end
		end
	end

	local res = {}
	copy(src, res)
	return res
end


---从数组中选出N个元素,等概率
---@param t_		table	源数组(不会被改动)
---@param count_	number	选的元素数量
---@return table
function _M.random_array( t_, count_ )
	if count_ <= 0 then
		return {}
	end

	local nt_ = shallow_copy(t_)
	for i = 1, 2 do
		_M.shuffle(nt_)	---洗两遍
	end

	local ret_ = {}
	for i, v in ipairs(nt_) do
		ret_[i] = v
		if i >= count_ then
			break
		end
	end
	return ret_
end


---在整数 start_ 到 end_ 的范围内,选出 count_ 个数字
---@param start_	number	整数区间起始值(含)
---@param end_		number	整数区间截止值(含)
---@param count_	number	选的元素数量
---@return table
function _M.random_array_number( start_, end_, count_ )
	if start_ > end_ or count_ <= 0 then
		return {}
	end

	local t_ = {}
	for i = start_, end_ do
		t_[#t_+1] = i
	end

	return _M.random_array( t_, count_ )
end


return _M;
